<?php

/**
 * 批量图片上传模型
 * @author perry
 */

namespace Admin\Model;

use Think\Model;

class MultiUploadPicModel extends Model {
	protected $tableName = 'bh_multi_upload_pic'; 

	function _initialize()
	{
		// $this->option = M('fotile520_option');
	}
	
	public function getByOriName($oriName,$type=1,$img_multi_hz=false){
		if($img_multi_hz===false){
			$img_multi_hz=C('img_multi_hz');
		}
		$oriName.=$img_multi_hz;
		$oriName=strtolower($oriName);
		$map=array('ori_name'=>$oriName,'type'=>$type);
		
		$re= $this->where($map)->find();
		return $re;
	}

	//根据图片保存文件名和用途去商品或造型数据查找该图是否被使用
	//type  1商品图，2造型图
	public function findUsedRecords($uni_name,$type=1){
		if($type==2){
			$lookExist=M('bh_looks')->field('id')->where(array('img'=>$uni_name))->find();
			if($lookExist){
				return array('used'=>true,'useby'=>'造型','datas'=>$lookExist);
			}
			$lookExist=M('bh_looks')->field('id')
			->where(array('sub_imgs'=>array('like','%'.$uni_name.'%')))->find();
			if($lookExist){
				return array('used'=>true,'useby'=>'造型副图','datas'=>$lookExist);
			}
		}
		if($type==1){
			$lookExist=M('bh_closet_commodity')->field('id')->where(array('img'=>$uni_name))->find();
			if($lookExist){
				return array('used'=>true,'useby'=>'商品首图','datas'=>$lookExist);
			}
			$lookExist=M('bh_closet_commodity')->field('id')
			->where(array('sub_imgs'=>array('like','%'.$uni_name.'%')))->find();
			if($lookExist){
				return array('used'=>true,'useby'=>'商品副图','datas'=>$lookExist);
			}
		}
		return array('used'=>false,'useby'=>false,'datas'=>array());
	}

	//检查本表所有图片在造型或商品数据里的使用情况
// 	ALTER TABLE `eosi_bh_multi_upload_pic`
// ADD COLUMN `is_using`  tinyint NOT NULL DEFAULT '-1' COMMENT '是否还被使用，0否1是' AFTER `update_time`,
// ADD UNIQUE INDEX `u_uni` (`uni_name`) USING BTREE ;
	public function checkAllPicUsed($type="",$beforeSeconds=300,$count=65536){
		$map=array();
		if(in_array($type, array(1,2))){
			$map['type']=$type;
		}
		$map['update_time']=array('exp',"<".(time()-$beforeSeconds));

		$all=$this->where($map)->field('ori_name,uni_name,id,create_time,type,is_using')
		->order('update_time asc')->limit($count)->select();
		// dump($all);
		if(!$all){
			return;
		}
		$debugarr=array();
		foreach ($all as $key => &$value) {
			$isUsed=$this->findUsedRecords($value['uni_name'],$value['type']);
			$value['is_using']=$isUsed['used']?1:0;
			$value['update_time']=time();
			$debugarr[]=$value['id'];
		}
		dump(implode(",", $debugarr));
		$this->addAll($all,array(),array('is_using','update_time'));
	}
}    